import * as Msal from 'msal'

export default class AuthService {
  constructor() {
    const PROD_REDIRECT_URI = 'http://localhost:9528/dashboard'
    let redirectUri = window.location.origin
    if (window.location.hostname !== '127.0.0.1') {
      redirectUri = PROD_REDIRECT_URI
    }

    this.msalApplicationConfig = {
      auth: {
        clientId: '77703e2b-f001-49d3-b5cc-ebf775f7a33e',
        redirectUri: redirectUri,
        authority: 'https://login.microsoftonline.com/qdlsai.org'
      },
      cache: {
        cacheLocation: 'localStorage',
        storeAuthStateInCookie: true
      },
      graphEndpoint: 'https://qdlsai.org/HSElearning.WebAPI',
      graphScopes: {
        scopes: ['user.read']
      }
    }
    this.msalApp = new Msal.UserAgentApplication(this.msalApplicationConfig)
    this.msalApp.handleRedirectCallback(function(_error, _response) {

    })
  }
  signIn() {
    this.msalApp.loginRedirect(this.msalApplicationConfig.graphScopes)
  }
  signOut() {
    this.msalApp.logout()
  }
  isAuthenticated() {
    if (this.msalApp.getAccount()) { return true }
    return false
  }
  getUserProfile() {
    return this.msalApp.getAccount()
  }
  acquireToken() {
    var tokenRequest = {
      scopes: ['https://qdlsai.org/HSElearning.WebAPI/user_impersonation']
    }
    // if the user is already logged in you can acquire a token
    if (this.msalApp.getAccount()) {
      return new Promise((resolve, reject) => {
        this.msalApp.acquireTokenSilent(tokenRequest)
          .then(response => {
          // get access token from response
            return resolve(response.accessToken)
          })
          .catch(err => {
          // could also check if err instance of InteractionRequiredAuthError if you can import the class.
            console.log(err)
            if (err.name === 'InteractionRequiredAuthError') {
              return this.msalApp.acquireTokenRedirect(tokenRequest)
                .then(response => {
                // get access token from response
                  return resolve(response.accessToken)
                })
                .catch(_err => {
                  console.log(_err)
                // handle error
                })
            }
          })
      })
    } else {
      // user is not logged in, you will need to log them in to acquire a token
      this.signIn()
    }

    // return this.msalApp.acquireTokenSilent(tokenRequest).then(
    //   accessToken => {
    //     debugger
    //     console.log('accessToken')
    //     console.log(accessToken)

    //     return accessToken.accessToken
    //   },
    //   error => {
    //     return this.msalApp
    //       .acquireTokenRedirect(tokenRequest)
    //       .then(
    //         accessToken => {
    //           debugger
    //           console.log('accessToken')
    //           console.log(accessToken)

    //           return accessToken
    //         },
    //         err => {
    //           console.error(err)
    //         }
    //       )
    //   }
    // )
  }
}
